<template>
  <ComWrapper>
    <el-card shadow="never" style="margin-bottom:20px">
      <el-input placeholder="请输入文件名" v-model="filename" />
      <el-button type="primary" @click="handleDownload">导出已选择的</el-button>
    </el-card>

    <el-table
      ref="multipleTableRef"
      :data="list"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column align="center" label="Id">
        <template #default="scope">
          {{ scope.$index }}
        </template>
      </el-table-column>
      <el-table-column label="Title">
        <template #default="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column label="Author" align="center">
        <template #default="scope">
          <el-tag>{{ scope.row.author }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Readings" align="center">
        <template #default="scope">
          {{ scope.row.readings }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="Date">
        <template #default="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.date }}</span>
        </template>
      </el-table-column>
    </el-table>
  </ComWrapper>
</template>

<script setup>
import {ref} from 'vue'
import {ElMessage} from 'element-plus'

const multipleTableRef = ref(null)
const filename = ref('')
const downloadLoading = ref(false)
const multipleSelection = ref([])
const list = ref([
  {
    id: 1,
    title: 'title--1',
    author: 'xjc',
    readings: 123,
    content: 'this is a content',
    date: '2020-10-2'
  },
  {
    id: 2,
    title: 'title--2',
    author: 'xjc',
    readings: 456,
    content: 'this is a content',
    date: '2020-10-2'
  },
  {
    id: 3,
    title: 'title--3',
    author: 'xjc',
    readings: 789,
    content: 'this is a content',
    date: '2020-10-2'
  }
])

function handleSelectionChange(val) {
  multipleSelection.value = val
}
function handleDownload() {
  const multiVal =  multipleSelection.value
  if (multiVal.length) {
    downloadLoading.value = true
    import('@/plugins/excel').then(excel => {
      const tHeader = ['id', 'title', 'author', 'readings', 'date']
      const filterVal = ['id', 'title', 'author', 'readings', 'date']
      const data = formatJson(filterVal, multiVal)
      excel.export_json_to_excel({
        header: tHeader,
        data,
        filename: filename.value
      })
      multipleTableRef.value.clearSelection()
      downloadLoading.value = false
    })
  } else {
    ElMessage({
      message: '至少要选择一项',
      type: 'warning'
    })
  }
}
function formatJson(filterVal, jsonData) {
  return jsonData.map(v => filterVal.map(j => v[j]))
}
</script>